<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Update Post</title>
    <!-- 引入 Bootstrap CSS -->
    <link href="/api/static/lib/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="/api/static/lib/editormd.min.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/editor-md/1.5.0/editormd.min.js"></script>
    <style>
        body {
            font-family: Arial, sans-serif;
        }
        .container {
            max-width: 90%;
        }
        .editor {
            width: 100%;
        }
    </style>
</head>
<body class="container mt-5">
    <h1 class="mb-4">Update Post</h1>
    <div class="editor">
        <form id="updatePostForm" class="form-group">
            <label for="filePath">File Path:</label>
            <input type="text" id="filePath" name="filePath" class="form-control mb-3" readonly>
            <button type="submit" class="btn btn-primary mt-3">Update</button>
            <div id="content-editor">
                <textarea id="content" name="content" style="display:none;"></textarea>
            </div>
            <br>
        </form>
    </div>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            var editor = editormd("content-editor", {
                width: "100%",
                height: 640,
                path: "/api/static/lib/",
                imageUpload: true,
                imageFormats: ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
                imageUploadURL: "/api/uploadImage",
                onload: function() {
                    // 初始化完成后执行的逻辑
                    const urlParams = new URLSearchParams(window.location.search);
                    const filePath = urlParams.get('file');

                    if (filePath) {
                        document.getElementById('filePath').value = filePath;
                        fetch(`/api/getContent?filePath=${encodeURIComponent(filePath)}`)
                            .then(response => response.json())
                            .then(data => {
                                editor.setMarkdown(data.content);
                            });
                    }
                }
            });

            // 捕获粘贴事件
            document.getElementById('content-editor').addEventListener('paste', function(event) {
                var clipboardData = event.clipboardData || window.clipboardData;
                var items = clipboardData.items;

                for (var i = 0; i < items.length; i++) {
                    if (items[i].type.indexOf("image") !== -1) {
                        var file = items[i].getAsFile();
                        var formData = new FormData();
                        formData.append("file", file);

                        fetch('/api/upload', {
                            method: 'POST',
                            body: formData
                        })
                        .then(response => response.json())
                        .then(data => {
                            if (data.result === "success") {
                                // 将图片URL插入到Editor.md编辑器中
                                editor.insertValue(`![image](${data.url})`);
                            } else {
                                alert("Image upload failed");
                            }
                        })
                        .catch(error => {
                            console.error('Error:', error);
                            alert("Image upload failed");
                        });

                        event.preventDefault();
                        break;
                    }
                }
            });

            document.getElementById('updatePostForm').addEventListener('submit', function(event) {
                event.preventDefault();
                const filePath = document.getElementById('filePath').value;
                const content = editor.getMarkdown();
                fetch('/api/hugo/update', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ filePath: filePath, content: content })
                })
                .then(response => {
                    if (response.ok) {
                        alert('File updated successfully');
                    } else {
                        response.json().then(data => {
                            alert(`Error: ${data.error}`);
                        });
                    }
                });
            });
        });
    </script>
    <!-- 引入 Bootstrap JS 和 jQuery -->
    <script src="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/4.5.2/js/bootstrap.min.js"></script>
</body>
</html>
